/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Services;

import java.io.Serializable;
import javax.persistence.*;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import Entity.MedicalRecord;
import Entity.Appointment;
import Entity.Vaccine;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author microraptor
 */
public class MedicalRecordService implements Serializable{
    private EntityManagerFactory emf = null;
    AppointmentService appointmentService = new AppointmentService(emf);
    VaccineService vaccineService = new VaccineService(emf);
    
    public MedicalRecordService (EntityManagerFactory emf){
        this.emf = emf;
    }
    
    public EntityManager getEntityManager(){
        return emf.createEntityManager();
    }
    
    public MedicalRecord findMedicalRecord2(Long id){
        EntityManager em = null;
        MedicalRecord medicalRecord = null;
        try{
            em = getEntityManager();
            medicalRecord = em.find(MedicalRecord.class, id);
        }finally{
            if(em != null){
                em.close();
            }
        }
        return medicalRecord;
    }
    
    public void crear(MedicalRecord medicalRecord){
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(medicalRecord);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public void edit(MedicalRecord medicalRecord) throws Exception{
        EntityManager em = null;
        try{
            em = getEntityManager();
            em.getTransaction().begin();
            medicalRecord = em.merge(medicalRecord);
            em.getTransaction().commit();
        }catch (Exception ex){
            String msg = ex.getLocalizedMessage();
            if (msg == null ||  msg.length() == 0){
                Long id = medicalRecord.getId();
                if (findMedicalRecord(id) == null){
                    throw new Exception("The pet with id "+id+" no longer exists.");
                }
            }
            throw ex;
        }finally{
            if (em != null){
                em.close();
            }
        }
    }
    
    public void destroy (Long id) throws Exception{
        EntityManager em = null;
        try{
            em=getEntityManager();
            em.getTransaction().begin();
            MedicalRecord medicalRecord;
            try{
                medicalRecord = em.getReference(MedicalRecord.class, id);
                medicalRecord.getId();
            }catch(EntityNotFoundException ex){
                throw new Exception ("The owner with id "+id+" no longer exists.", ex);
            }
            em.remove(medicalRecord);
            em.getTransaction().commit();
        }finally{
            if(em != null){
                em.close();
            }
        }
    }
    
    public List<MedicalRecord> findMedicalRecordEntities(){
        return findMedicalRecordEntities(true, -1,-1);
    }
    
    public List<MedicalRecord> findMedicalRecordEntities(int maxResults, int firstResult){
        return findMedicalRecordEntities(false, maxResults, firstResult);
    }
    
    private List<MedicalRecord> findMedicalRecordEntities(boolean all, int maxResults, int firstResult)    {
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq =  em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(MedicalRecord.class));
            Query q = em.createQuery(cq);
            if(!all){
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            
            for (int i =0;i<q.getResultList().size(); i++){
                MedicalRecord medicalRecord = (MedicalRecord) q.getResultList().get(i);
                long medicalRecordId = medicalRecord.getId();
                Query query1 = em.createNativeQuery("select vaccines from MedicalRecord_vaccines)"
                        + " where MedicalRecord_ID = " + medicalRecordId);
                Query query2 = em.createNativeQuery("select appoinments from MedicalRecord_appoinments)"
                        + " MedicalRecord_ID = " + medicalRecordId);
            
                medicalRecord.setAppointments(findAppointments(query1));
                medicalRecord.setVaccines(findVaccines(query2));
            }   
            return q.getResultList();
        }finally{
            em.close();
        }
    }
    
    @SuppressWarnings ("empty-statement")
    public MedicalRecord findMedicalRecord(Long id){
        EntityManager em = getEntityManager();
        try{
            MedicalRecord medicalRecord = em.find(MedicalRecord.class, id);
            long medicalRecordId = medicalRecord.getId();
            Query query1 = em.createNativeQuery("select vaccines from MedicalRecord_vaccines"
                        + " where MedicalRecord_ID = " + medicalRecordId);
            Query query2 = em.createNativeQuery("select appoinments from MedicalRecord_appoinments"
                        + " MedicalRecord_ID = " + medicalRecordId);
            
            medicalRecord.setAppointments(findAppointments(query1));
            medicalRecord.setVaccines(findVaccines(query2));
            
            return medicalRecord;
        }finally{
            em.close();
        }
    }
    
    private List<Vaccine> findVaccines(Query query){
        List<Vaccine> vaccines = new ArrayList<>();
        for(int i=0; i<query.getResultList().size(); i++){
            Long vaccineId = (Long) query.getResultList().get(i);
            vaccines.add(vaccineService.findVaccine(vaccineId));
        }
        return vaccines;
    }
    
    private List<Appointment> findAppointments(Query query){
        List<Appointment> appointments = new ArrayList<>();
        for(int i=0; i<query.getResultList().size(); i++){
            Long appointmentId = (Long) query.getResultList().get(i);
            appointments.add(appointmentService.findAppointment(appointmentId));
        }
        return appointments;
    }
    
    public int getAppointmentCount(){
        EntityManager em = getEntityManager();
        try{
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<MedicalRecord> rt = cq.from(MedicalRecord.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long)q.getSingleResult()).intValue();
        }finally{
            em.close();
        }
    }
}
